<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */

defined('IN_AGORA') or die;

require_once('agora.common.php');

class Agora extends AgoraCommon {
	function showMessage($msg, $type = 'message') {
		$mainframe = & JFactory::getApplication();
		$mainframe->enqueueMessage($msg, $type);
	}

	function showError($e) {
		Agora::showMessage(Agora::lang($e),'error');
	/*
		if (Agora::isPOST()) {
			Agora::redirect();
		}
	*/
	}

	function getRoot() {
		return JURI::base().'components/com_agora/';
	}

	function getSite() {
		return JURI::root().'components/com_agora/';
	}

	function escape($key) {
		return htmlspecialchars($key, ENT_QUOTES, 'UTF-8');
	}

	function getCurrentLanguage() {
		static $lang;
		if (!$lang) {
			$lang = & JFactory::getLanguage();
		}

		return $lang->getTag();
	}
	
	function config() {
		static $cfg;
		if (!isset($cfg)) {
			$config = & Model::getInstance('ConfigModel');
			$cfg = $config->load();
		}
		return $cfg;
	}
	
	function image($image)
	{
		if (is_array($image)) {
			$image = implode('/', $image);
		}
		$image = (string) $image;
		// external/full path? just return the string
		// note that double slash //
		// is all that's really necessary, so watch your paths!
		if (preg_match('/^(?:https?\:)?\/{2}/i', $image)) {
			return $image;
		}
		// import filesystem classes
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');
		// clean up path a wee bit :)
		$image = trim(str_replace('\\', '/', $image), '/');
		while (false !== strpos($image, '..')) {
			$image = str_replace('..', '', $image);
		}
		// start with template override
		$tmpl = JFactory::getApplication()->getTemplate();
		$templatePath = JPATH_ROOT . DS . 'templates' . DS . $tmpl . DS . 'images' . DS . 'com_agora';
		$config = self::config();
		// see if the image exists as a template override
		if (JFile::exists($templatePath . DS . $image)) {
			return JURI::root() . '/templates/' . $tmpl . '/images/com_agora/' . $image; 
		}
		// see if the image exists in the current style
		else if (JFile::exists(AGORA_PATH . DS . 'style' . DS . $config['o_default_style'] . DS . 'img' . DS . $image)) {
			return Agora::getRoot() . 'style/' . $config['o_default_style'] . '/img/' . $image;
		}
		// no override? get default
		else if (JFile::exists(AGORA_PATH . DS . 'img' . DS . $image)) {
			return Agora::getRoot() . 'img/' . $image;
		}
		// ouch, no image... bail?
		return '';
	}

	function lang($key) {
		static $jlang = null;

		if (is_null($jlang)) {
			$jlang = & JFactory::getLanguage();
		}

		if (is_array($key)) {
			// key from preg_replace_callback
			$key = $key[1];
		}

//		$result = addslashes($jlang->_(/*str_replace(' ','_',*/trim($key)/*)*/,false));
		$result = $jlang->_(trim($key));

		$args = func_get_args();
		if (count($args) > 1) {
			$args[0] = $result;
			$result = call_user_func_array('sprintf',$args);
		}

		if (defined('AGORA_HELP_TRANSLATE')) {
			echo $key.' '.'&nbsp;-&nbsp;';

			if ($key !== $result && '??'.$key.'??' !== $result) {
				echo 'TRANSLATED';
			} else {
				echo '<b>NOT FOUND</b>';
			}
			print "<br />\n";
		
		}

		return Agora::escape($result);
	}

	function linebreaks($str) {
		return str_replace("\r", "\n", str_replace("\r\n", "\n", $str));
	}

	function filterForm(& $form, $fields) {
		if (!is_array($fields)) return;
		$keys = array();
		foreach ($fields as $key => $value) {
			if (is_string($key)) {
				$form_key = $key;
				$form_value = $value;
			} else {
				$form_key = $value;
				$form_value = 0;
			}
			if (!isset($form[$form_key])) {
				$form[$form_key] = $form_value;
			}
			$keys[] = $form_key;
		}

		foreach ($form as $form_key=>$form_value) {
			if (!in_array($form_key,$keys)) {
				unset($form[$form_key]);
			}
		}
	}

	function redirect($url = NULL, $same_window = false) {
		if (!$url) {
			$uri = JURI::getInstance();
			$url = $uri->toString();
		}
		// if (headers_sent()) {
		@ob_end_clean();

		if (Agora::getRequestVar('type') == 'clean' && !$same_window) {
			//popup box
			echo '<script type="text/javascript">window.top.location.href="'.html_entity_decode($url).'"; window.parent.document.getElementById(\'sbox-window\').close();</script>\n';
		} elseif (Agora::isPost()) {
			header( 'HTTP/1.1 303 See other' );
			header( 'Location: ' . html_entity_decode($url), true);
			header( 'Allow: GET');
		// echo '<script type="text/javascript">document.location.href="'.html_entity_decode($url).'";</script>\n';
		} else {
			header( 'HTTP/1.1 303 See other' );
			header( 'Location: ' . html_entity_decode($url), true);
			header( 'Allow: GET');
		}
		// Persist messages if they exist

		$mainframe = & JFactory::getApplication();

		if (count($mainframe->_messageQueue)) {
			$session =& JFactory::getSession();
			$session->set('application.queue', $mainframe->_messageQueue);
		}

		/*		
		} else {
			@ob_end_clean(); // clear output buffer
			header( 'HTTP/1.1 303 See other' );
			header( 'Location: ' . $url, true);
			echo "\n\nRedirecting to $url";
		}*/
		/*
		$mainframe = & JFactory::getApplication();
		$mainframe->redirect($url);
		*/
		die;
	}

	function redirect301($url = NULL, $same_window = false) {
		if (!$url) {
			$uri = JURI::getInstance();
			$url = $uri->toString();
		}
		@ob_end_clean();

		if (Agora::getRequestVar('type') == 'clean' && !$same_window) {
			//popup box
			echo '<script type="text/javascript">window.top.location.href="'.html_entity_decode($url).'"; window.parent.document.getElementById(\'sbox-window\').close();</script>\n';
		} elseif (Agora::isPost()) {
			header( 'HTTP/1.1 301 Moved Permanently' );
			header( 'Location: ' . html_entity_decode($url), true);
			header( 'Allow: GET');
		} else {
			header( 'HTTP/1.1 301 Moved Permanently' );
			header( 'Location: ' . html_entity_decode($url), true);
			header( 'Allow: GET');
		}
		// Persist messages if they exist

		$mainframe = & JFactory::getApplication();

		if (count($mainframe->_messageQueue)) {
			$session =& JFactory::getSession();
			$session->set('application.queue', $mainframe->_messageQueue);
		}
		die;
	}

	function show404() {
		JError::raiseError( 404, JText::_('Page Not Found') );
	}

	function getVar($var, $def = null) {
		return JRequest::getVar($var, $def, 'GET');
	}

	function getRequestVar($var, $def = null) {
		return JRequest::getVar($var, $def, 'REQUEST');
	}

	function getPostVar($var,$def = null, $raw = false) {
		return JRequest::getVar($var, $def, 'POST', 'none', $raw ? 2 : 0);
	}

	function getSessionVar($var, $def = null) {
		$sess = JFactory::getSession();
		return $sess->get($var, $def, 'agora');
	}

	function setSessionVar($var, $value) {
		$sess = JFactory::getSession();
		$sess->set($var, $value, 'agora');
	}

	function isFeed() {
		$format = JRequest::getWord('format');
		if ($format === 'feed') {
			return true;
		}
		return false;
	}

	function getFeedType() {
		$type = JRequest::getWord('type','rss');
		return $type;
	}

	function getSelf() {
		$uri = & JFactory::getURI();
		return $uri->toString();
	}

	function makeFeedURL($params) {
		$url = 'index.php?option=com_agora';
		//~ $url = '?option=com_agora';
		foreach ($params as $name => $value) {
			$url .= "&$name=$value";
		}
		
		/*
		global $Itemid;

		if (isset($Itemid)) {
			$url .= '&Itemid='.$Itemid;
		}
		*/
		
		//~ $uri = JURI::getInstance();
		//~ $ret = $uri->getPath().Agora::escape($url)
		
		$ret = JRoute::_($url);
		
		return $ret;
	}

	function makeURL($params, $html = true, $agroup = false) {
		static $isAdmin = null;

		if (is_null($isAdmin)) {
			$app = JFactory::getApplication();
			$isAdmin = $app->isAdmin();
		}
		
		$pos1 = strpos($_SERVER['PHP_SELF'], '/');
		$pos2 = strpos($_SERVER['PHP_SELF'], '/index');
		$prefics = substr($_SERVER['PHP_SELF'], $pos1, $pos2-$pos1);
		$prefics .= '/';
		
		if (isset($params['option'])) {
		    if ($agroup)
			$url = 'index2.php?option='.$params['option'];
			else
			$url = 'index.php?option='.$params['option'];

			if (!isset($params['Itemid'])) {
				$component	= &JComponentHelper::getComponent($params['option']);
				$menu		= &JSite::getMenu();
				$items		= $menu->getItems('componentid', $component->id);
				if (is_array($items) && count($items) > 0) {
					$url .= '&Itemid='.$items[0]->id;
				}
			}

			unset($params['option']);
		} else {
			static $agora_itemid;

			if (!isset($params['Itemid']) && !$isAdmin) {
				if (!isset($agora_itemid)) {
					$agora_itemid = Agora::getVar('Itemid');
					if (is_null($agora_itemid)) {
						$component	= &JComponentHelper::getComponent('com_agora');
						$menu		= &JSite::getMenu();
						$items		= $menu->getItems('componentid', $component->id);
						if (is_array($items) && count($items) > 0) {
							$agora_itemid = $items[0]->id;
						}
					}
				}
				if ($agora_itemid) {
					$params['Itemid'] = $agora_itemid;
				}
			}
            if ($agroup)
			$url = $prefics.'index2.php?option=com_agora';
			else
			$url = 'index.php?option=com_agora';
		}
		$hash = '';
	
		if (isset($params['task']) && $params['task'] == 'rss' && isset($params['Itemid'])) {
			unset($params['Itemid']);
		}
		
		$p = 0;
		
		foreach ($params as $name => $value) {
			// skip "p" when p <= 1 so we don't end up with duplicates
			// add "p" at the end (why? because the router is STUPID)
			if ('p' == $name) {
				if (1 >= intval($value)) continue;
				$p = intval($value);
				continue;
			}
			// build
			if ($name != '_') {
				$url .= '&'.$name.'='.$value;
			} else {
				$hash = '#'. $value;
			}
		}
		
		// here's that "add p to the end, stupid router" shit
		if ($p) $url .= '&p=' . $p;
		
		$uri    = & JURI::getInstance();

		if ($isAdmin) {
			$prefix = '';
		} else {
			$prefix = $uri->toString(array('scheme', 'host', 'port'));
		}

		return $prefix . Agora::routeURL($url, $html). $hash;
	}

	function routeURL($url,$html = true) {
    	$url = JRoute::_($url, false);
    	
		if ($html) {
			$url = htmlspecialchars($url);
		}
		return preg_replace('/[&\?]$/','',$url);
	}

	function isPOST() {
		if (JRequest::getMethod() === 'POST') {
			return true;
		}
		return false;
	}
}

?>